﻿/*
 *      CentroVentasCore32  - CVCore32.dll
 *      
 *      Desarrollado por:
 *                      Francisco Acevedo.
 *                      David Avila.
 *                      José Pérez.
 *                      
 *      Todos los derechos reservados.
 */

/*
 *      CLASE: CarroCompras   
 * Notas de versión:
 * 
 * [19-03-2012]
 *      -   Creación de la clase.
 *      -   Agregado metodos importantes.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace CVCore32.Class.Funciones.Compras
{
    [System.Runtime.InteropServices.GuidAttribute("E0D76AE2-5F2E-42EE-AE47-FE72C1FF7591")]
    public class Compras
    {
        public static string GetCodCompra()
        {
            Core.Sesion sesion = Core.Sesion.GetInstace;
            Data.electrondbEntities context;
            if (sesion.ServidorWeb)
            {
                context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;");
            }
            else
            {
                context = new Data.electrondbEntities();
            }

            var Orden = (from o in context.Compra
                         select o.CompraId).Count();

            return Orden.ToString().PadLeft(8, '0');

        }

        public static int Comprar(int proveedor, string comentarios, int[] precios)
        {

            CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;

            if (sesion.ServidorWeb)
            {
                using (Data.electrondbEntities context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;"))
                {
                    context.Connection.Open();
                    using (var transaction = context.Connection.BeginTransaction())
                    {
                        try
                        {

                            Data.Compra comp = new Data.Compra()
                            {
                                Orden = GetCodCompra(),
                                Usuario = sesion.IdUsuario,
                                Proveedor = proveedor,
                                FechaPedido = DateTime.Now,
                                Comentarios = comentarios,
                                TipoPago = 1,
                                Estado = 2,
                                Documento = String.Empty
                            };
                            context.AddToCompra(comp);

                            foreach (int item in precios)
                            {
                                Data.DetalleCompra detcomp = new Data.DetalleCompra()
                                {
                                    Compra = comp.CompraId,
                                    Precio = item
                                };
                                context.AddToDetalleCompra(detcomp);
                            }

                            context.SaveChanges();
                            transaction.Commit();
                            return comp.CompraId;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception(ex.InnerException.ToString());
                        }
                    }
                }
            }
            else
            {
                using (Data.electrondbEntities context = new Data.electrondbEntities())
                {
                    context.Connection.Open();
                    using (var transaction = context.Connection.BeginTransaction())
                    {
                        try
                        {

                            Data.Compra comp = new Data.Compra()
                            {
                                Orden = GetCodCompra(),
                                Usuario = sesion.IdUsuario,
                                Proveedor = proveedor,
                                FechaPedido = DateTime.Now,
                                Comentarios = comentarios,
                                TipoPago = 1,
                                Estado = 2,
                                Documento = String.Empty
                            };
                            context.AddToCompra(comp);

                            foreach (int item in precios)
                            {
                                Data.DetalleCompra detcomp = new Data.DetalleCompra()
                                {
                                    Compra = comp.CompraId,
                                    Precio = item
                                };
                                context.AddToDetalleCompra(detcomp);
                            }

                            context.SaveChanges();
                            transaction.Commit();
                            return comp.CompraId;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception(ex.InnerException.ToString());
                        }
                    }
                }
            }
        }

        public static IBindingList GetComprasList()
        {
            CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;
            Data.electrondbEntities context;

            if (sesion.ServidorWeb)
            {
                context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;");
            }
            else
            {
                context = new Data.electrondbEntities();
            }
            IBindingList compras;

            compras = ((from p in context.Compra
                        select new
                        {
                            p.CompraId,
                            p.Orden,
                            p.Usuario1.NombreUsuario,
                            p.Estado1.EstadoDescripcion
                        }) as IListSource).GetList() as IBindingList;
            return compras;
        }

        public static IBindingList GetComprasList(string buscar, bool Finalizados)
        {
            throw new NotImplementedException();
        }

        public static object GetComprasList(string buscar)
        {
            throw new NotImplementedException();
        }

        public static bool ExisteCodigo(string codigo)
        {
            if (!String.IsNullOrWhiteSpace(codigo))
            {
                CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;
                Data.electrondbEntities context;
                if (sesion.ServidorWeb)
                {
                    context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;");
                }
                else
                {
                    context = new Data.electrondbEntities();
                }

                var compra = (from cat in context.Compra
                              where cat.Orden == codigo
                              select cat.CompraId).Count();

                if (compra != 0)
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }

        public static Data.Compra GetCompra(string orden)
        {
            try
            {
                CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;
                Data.electrondbEntities context;
                if (sesion.ServidorWeb)
                {
                    context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;");
                }
                else
                {
                    context = new Data.electrondbEntities();
                }

                Data.Compra compra = (from com in context.Compra
                                      where com.Orden == orden
                                      select com).SingleOrDefault();
                return compra;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static IBindingList GetDetalleCompra(string orden)
        {
            try
            {
                CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;
                Data.electrondbEntities context;
                if (sesion.ServidorWeb)
                {
                    context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;");
                }
                else
                {
                    context = new Data.electrondbEntities();
                }

                IBindingList DetalleCompra = ((from d in context.DetalleCompra
                                               where d.Compra1.Orden == orden
                                               select new
                                               {
                                                   d.Precio1.Producto1.CodBarras,
                                                   d.Precio1.Producto1.Descripcion,
                                                   d.Precio1.Cantidad,
                                                   d.Precio1.Costo
                                               }) as IListSource).GetList() as IBindingList;
                return DetalleCompra;
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }

        public static Double GetTotalCompra(string orden)
        {
            try
            {
                CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;
                Data.electrondbEntities context;
                if (sesion.ServidorWeb)
                {
                    context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;");
                }
                else
                {
                    context = new Data.electrondbEntities();
                }

                List<Data.Precio> pre = (from v in context.DetalleCompra
                                         where v.Compra1.Orden == orden
                                         select v.Precio1).ToList();
                double total = 0;
                foreach (Data.Precio p in pre)
                {
                    total = Convert.ToDouble(p.Costo) * p.Cantidad;
                }
                return total;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static bool ConfirmarCompra(string orden)
        {
            try
            {
                CVCore32.Class.Core.Sesion sesion = CVCore32.Class.Core.Sesion.GetInstace;
                if (sesion.ServidorWeb)
                {
                    using (Data.electrondbEntities context = new Data.electrondbEntities("Data Source=72.18.135.49, 1533;Initial Catalog=electrondb;User Id=JotaEmePM;Password=ez881010;"))
                    {
                        context.Connection.Open();
                        using (var transaction = context.Connection.BeginTransaction())
                        {
                            try
                            {
                                Data.Compra c = context.Compra.First(i => i.Orden == orden);
                                c.Estado = 3;
                                c.FechaPago = DateTime.Now;
                                c.FechaFechaRecivo = DateTime.Now;

                                List<Data.Precio> precio = (from pr in context.DetalleCompra
                                                            where pr.Compra1.Orden == orden
                                                            select pr.Precio1).ToList();

                                foreach (Data.Precio p in precio)
                                {
                                    p.Valido = 1;
                                }

                                context.SaveChanges();
                                transaction.Commit();
                                return true;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception(ex.InnerException.ToString());
                            }
                        }                        
                    }
                }
                else
                {
                    using (Data.electrondbEntities context = new Data.electrondbEntities())
                    {
                        context.Connection.Open();
                        using (var transaction = context.Connection.BeginTransaction())
                        {
                            try
                            {
                                Data.Compra c = context.Compra.First(i => i.Orden == orden);
                                c.Estado = 3;
                                c.FechaPago = DateTime.Now;
                                c.FechaFechaRecivo = DateTime.Now;

                                List<Data.Precio> precio = (from pr in context.DetalleCompra
                                                            where pr.Compra1.Orden == orden
                                                            select pr.Precio1).ToList();

                                foreach(Data.Precio p in precio)
                                {
                                    p.Valido = 1;
                                }                                
                                
                                context.SaveChanges();                                
                                transaction.Commit();
                                return true;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception(ex.InnerException.ToString());
                            }
                        }                        
                    }
                }
            }
            catch (Exception ex)
            {                
                throw new Exception(ex.Message);
            }
        }

    }
}
